package com.sfac.day03.modules.account.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sfac.day03.modules.account.dao.RoleDao;
import com.sfac.day03.modules.account.dao.RoleResourceDao;
import com.sfac.day03.modules.account.dao.UserRoleDao;
import com.sfac.day03.modules.account.entity.Role;
import com.sfac.day03.modules.account.service.RoleService;
import com.sfac.day03.modules.common.entity.ResultEntity;
import com.sfac.day03.modules.common.entity.SearchBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleResourceDao roleResourceDao;
    @Override
    @Transactional
    public ResultEntity<Role> insertRole(Role role) {
        role.setCreateDate(LocalDateTime.now());
        roleDao.insertRole(role);
        return new ResultEntity<Role>(200,"insert sucess",role);
    }

    @Override
    @Transactional
    public ResultEntity<Role> updateRole(Role role) {
        roleDao.updateRole(role);
        return new ResultEntity<Role>(200,"update sucess",role);
    }

    @Override
    @Transactional
    public ResultEntity<Object> deleteRoelById(int id) {
        roleDao.deleteRole(id);
        userRoleDao.deleteUserRoleByRoleId(id);
        roleResourceDao.deleteRoleResourceByRoleId(id);
        return new ResultEntity<Object>(200,"delete sucess");
    }

    @Override
    public Role getRoleById(Integer id) {
        Role roleById = roleDao.getRoleById(id);
        return roleById;
    }

    @Override
    public List<Role> getRolesByUserId(Integer userId) {
        return  Optional.ofNullable(roleDao.getRolesByUserId(userId)).orElse(Collections.emptyList());
    }

    @Override
    public List<Role> getRoles() {
        return roleDao.getRoles();
    }

    @Override
    public PageInfo<Role> getRolesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getPageNumber(),searchBean.getPageSize());
        return new PageInfo<>(Optional.ofNullable(roleDao.getRolesBySearchBean(searchBean)).orElse(Collections.emptyList()));
    }
}
